package com.crm.model.dto;

import com.alibaba.fastjson.JSONObject;
import com.crm.common.model.Enum.StatusCodeEnum;
import com.crm.common.util.CommonUtils;
import com.crm.model.entity.cluePoolManager.ClueFollow;
import com.crm.model.entity.contactManager.Contact;
import com.crm.model.entity.contactManager.ContactErrorRecord;
import com.crm.model.entity.contactManager.ContactInformation;
import com.crm.model.entity.customerManager.*;
import com.crm.model.entity.sys.ImportFailureLog;
import com.crm.model.entity.sys.UserAccount;
import com.crm.model.entity.sys.permissionManagement.SysCompany;
import com.crm.model.vo.cluePoolManager.ClueFollowVO;
import com.crm.model.vo.cluePoolManager.ImportFollowVO;
import com.crm.model.vo.customerManager.CustomerVO;
import com.crm.model.vo.systemManager.ContactImportVO;
import com.crm.model.vo.user.UserAccountManagerVO;
import com.crm.service.contactManager.ContactDbService;
import com.crm.service.contactManager.ContactInformationDbService;
import com.crm.service.customerManager.CustomerDbService;
import com.crm.service.customerManager.CustomerPoolDbService;
import com.crm.service.customerManager.SingleProductCustomerContactDbService;
import com.crm.service.customerManager.SingleProductCustomerDbService;
import com.crm.service.sys.ImportFailureLogDbService;
import com.crm.service.sys.UserAccountDbService;
import com.crm.service.sys.permissionManagement.SysCompanyDbService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.User;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;

/**
 * @Author:baijian
 * @Date: 2021/6/26 9:19
 */
@Slf4j
public class InsertContactCallable implements Callable<JSONObject> {


    private ContactDbService contactDbService;
    private CustomerPoolDbService customerPoolDbService;
    private ContactInformationDbService contactInformationDbService;
    private CustomerDbService customerDbService;
    private UserAccountDbService userAccountDbService;
    private ImportFailureLogDbService importFailureLogDbService;
    private SysCompanyDbService sysCompanyDbService;
    private SingleProductCustomerDbService singleProductCustomerDbService;
    private SingleProductCustomerContactDbService singleProductCustomerContactDbService;
    private List<ContactImportVO> list;
    private CountDownLatch begin;
    private CountDownLatch end;
    private String companyId;

    public InsertContactCallable(ContactDbService contactDbService, CustomerPoolDbService customerPoolDbService,
                                 ContactInformationDbService contactInformationDbService, CustomerDbService customerDbService,
                                 UserAccountDbService userAccountDbService, ImportFailureLogDbService importFailureLogDbService,
                                 SysCompanyDbService sysCompanyDbService,SingleProductCustomerDbService singleProductCustomerDbService,
                                 SingleProductCustomerContactDbService singleProductCustomerContactDbService,
                                 List<ContactImportVO> list, CountDownLatch begin, CountDownLatch end, String companyId) {
        this.contactDbService = contactDbService;
        this.customerPoolDbService = customerPoolDbService;
        this.contactInformationDbService = contactInformationDbService;
        this.customerDbService = customerDbService;
        this.userAccountDbService = userAccountDbService;
        this.importFailureLogDbService = importFailureLogDbService;
        this.sysCompanyDbService = sysCompanyDbService;
        this.singleProductCustomerDbService = singleProductCustomerDbService;
        this.singleProductCustomerContactDbService = singleProductCustomerContactDbService;
        this.list = list;
        this.begin = begin;
        this.end = end;
        this.companyId = companyId;
    }

    @SneakyThrows
    @Override
    public JSONObject call() {
        log.info("当前线程开始导入: {}",Thread.currentThread().getId());
        //导入数量
        int importNum = 0;
        //重复的行数
        List<Integer> repeatIdStr = new ArrayList();
        //失败行数
        List<Integer> importFailIdStr = new ArrayList();

        String content = "导入异常";
        UserAccount userAccount = null;
        JSONObject jsonObject = new JSONObject();
        Boolean b = false;

        for (int i = 0; i < list.size(); i++) {
            ContactImportVO importVO = list.get(i);
            try {
                //查询客户是否存在
                Customer customer = null;
                if (!StringUtils.isBlank(importVO.getAccountName())) {
                    userAccount = userAccountDbService.selectUserAccountByUserNameAndCompanyId(importVO.getAccountName(),companyId);
                } else {
                    content = "所有人姓名为空,联系人姓名:"+ importVO.getContactName() + ",主手机:"+ importVO.getContactInformation()
                            + ",电话:" + importVO.getInformation() + ",客户姓名:" + importVO.getCustomerName()
                            + ",所有人:" + importVO.getAccountName() + ",所属分公司:" + importVO.getCompanyName();
                    insertImportFailureLog(importVO, 2,content, "",companyId,"");
                    importFailIdStr.add(i+2);
                    continue;
                }

                if (userAccount != null) {
                    if (!StringUtils.isBlank(importVO.getCustomerName())) {
                        customer = customerDbService.selectCustomerNameAndAccountId(userAccount.getAccountId(), importVO.getCustomerName());
                    } else {
                        CustomerVO cust = customerDbService.selectCustomerByNameAndAccountId(importVO.getContactName(),userAccount.getAccountId(),"1",companyId);
                        if(cust == null) {
                            String contactId = CommonUtils.getGUID();
                            if(!StringUtils.isBlank(importVO.getContactName())){
                                if (!StringUtils.isBlank(importVO.getContactInformation())) {
                                    String information = "";
                                    if(importVO.getContactInformation().contains(",")) {
                                        String[] split = importVO.getContactInformation().split(",");
                                        information = split[0];
                                    }else{
                                        information = importVO.getContactInformation();
                                    }
                                    information = containsLine(information);
                                    //CustomerVO cust = customerDbService.selectCustomerByNameAndAccountId(importVO.getCustomerName(),userAccount.getAccountId(),"1");

                                    String customerId = addPersonalCustomer(importVO, userAccount,companyId);
                                    Customer cust1 = customerDbService.selectCustomerById(customerId);
                                    List<Contact> contactList = contactDbService.getCustomerIdAndContactNameAndAccountIdAndCompanyIds(customerId, importVO.getContactName(), information, "1", userAccount.getAccountId(),companyId);
                                    if (contactList.size() == 0) {
                                        Boolean c =  addContact(importVO, userAccount, cust1, contactId, companyId);
                                        if (c) {
                                            importNum = importNum + 1;
                                            continue;
                                        } else {
                                            content = "导入异常,联系人姓名:"+ importVO.getContactName() + ",主手机:"+ importVO.getContactInformation()
                                                    + ",电话:" + importVO.getInformation() + ",客户姓名:" + importVO.getCustomerName()
                                                    + ",所有人:" + importVO.getAccountName() + ",所属分公司:" + importVO.getCompanyName();
                                            insertImportFailureLog(importVO, 2, content, "",companyId,userAccount.getAccountId());
                                            importFailIdStr.add(i+2);
                                            continue;
                                        }
                                    } else {
                                        //insertImportFailureLog(importVO, 1, "联系人已存在", contactList.get(0).getContactId(),companyId);
                                        repeatIdStr.add(i+2);
                                        continue;
                                    }
                                } else {
                                    if (!StringUtils.isBlank(importVO.getInformation())) {
                                        String information = "";
                                        if (importVO.getInformation().contains(",")) {
                                            String[] informationArr = importVO.getInformation().split(",");
                                            information = informationArr[0];
                                        } else {
                                            information = importVO.getInformation();
                                        }
                                        information = containsLine(information);
                                        String customerId = addPersonalCustomer(importVO, userAccount,companyId);
                                        Customer cust1 = customerDbService.selectCustomerById(customerId);
                                        List<Contact> contactList = contactDbService.getCustomerIdAndContactNameAndAccountIdAndCompanyIds(customerId, importVO.getContactName(),information, "1", userAccount.getAccountId(),companyId);
                                        if (contactList.size() == 0) {
                                            Boolean c = addContact(importVO, userAccount, cust1, contactId, companyId);
                                            if (c) {
                                                importNum = importNum + 1;
                                                continue;
                                            } else {
                                                content = "导入异常,联系人姓名:"+ importVO.getContactName() + ",主手机:"+ importVO.getContactInformation()
                                                        + ",电话:" + importVO.getInformation() + ",客户姓名:" + importVO.getCustomerName()
                                                        + ",所有人:" + importVO.getAccountName() + ",所属分公司:" + importVO.getCompanyName();
                                                insertImportFailureLog(importVO, 2, content, "",companyId,userAccount.getAccountId());
                                                importFailIdStr.add(i+2);
                                                continue;
                                            }
                                        } else {
                                            //insertImportFailureLog(importVO, 1, "联系人已存在", contactList.get(0).getContactId(),companyId);
                                            repeatIdStr.add(i+2);
                                            continue;
                                        }
                                    } else {
                                        content = "没有电话号,联系人姓名:"+ importVO.getContactName() + ",主手机:"+ importVO.getContactInformation()
                                                + ",电话:" + importVO.getInformation() + ",客户姓名:" + importVO.getCustomerName()
                                                + ",所有人:" + importVO.getAccountName() + ",所属分公司:" + importVO.getCompanyName();
                                        insertImportFailureLog(importVO, 2, content, "",companyId,userAccount.getAccountId());
                                        importFailIdStr.add(i+2);
                                        continue;
                                    }
                                }
                            }else{
                                content = "联系人姓名不存在,联系人姓名:"+ importVO.getContactName() + ",主手机:"+ importVO.getContactInformation()
                                        + ",电话:" + importVO.getInformation() + ",客户姓名:" + importVO.getCustomerName()
                                        + ",所有人:" + importVO.getAccountName() + ",所属分公司:" + importVO.getCompanyName();
                                insertImportFailureLog(importVO, 2, content, "",companyId,userAccount.getAccountId());
                                importFailIdStr.add(i+2);
                                continue;
                            }
                        }
                    }




                    if (!StringUtils.isBlank(customer.getCustomerId()) && customer != null) {
                        String contactId = CommonUtils.getGUID();
                        if(!StringUtils.isBlank(importVO.getContactName())){
                            if (!StringUtils.isBlank(importVO.getContactInformation())) {
                                String information = "";
                                if(importVO.getContactInformation().contains(",")) {
                                    String[] split = importVO.getContactInformation().split(",");
                                    information = split[0];
                                }else{
                                    information = importVO.getContactInformation();
                                }
                                information = containsLine(information);
                                List<Contact> contactList = contactDbService.getCustomerIdAndContactNameAndAccountIdAndCompanyIds(customer.getCustomerId(), importVO.getContactName(), information, customer.getCustomerType(), userAccount.getAccountId(),companyId);
                                if (contactList.size() == 0) {
                                    Customer cust1 = customerDbService.selectCustomerById(customer.getCustomerId());
                                    Boolean c = addContact(importVO, userAccount, cust1, contactId, companyId);
                                    if (c) {
                                        importNum = importNum + 1;
                                        continue;
                                    } else {
                                        content = "导入异常,联系人姓名:"+ importVO.getContactName() + ",主手机:"+ importVO.getContactInformation()
                                                + ",电话:" + importVO.getInformation() + ",客户姓名:" + importVO.getCustomerName()
                                                + ",所有人:" + importVO.getAccountName() + ",所属分公司:" + importVO.getCompanyName();
                                        insertImportFailureLog(importVO, 2, content, "",companyId,userAccount.getAccountId());
                                        importFailIdStr.add(i+2);
                                        continue;
                                    }
                                } else {
                                    //insertImportFailureLog(importVO, 1, "联系人已存在", contactList.get(0).getContactId(),companyId);
                                    repeatIdStr.add(i+2);
                                    continue;
                                }
                            } else {
                                if (!StringUtils.isBlank(importVO.getInformation())) {
                                    String information = "";
                                    if (importVO.getInformation().contains(",")) {
                                        String[] informationArr = importVO.getInformation().split(",");
                                        information = informationArr[0];
                                    } else {
                                        information = importVO.getInformation();
                                    }
                                    information = containsLine(information);
                                    List<Contact> contactList = contactDbService.getCustomerIdAndContactNameAndAccountIdAndCompanyIds(customer.getCustomerId(), importVO.getContactName(),information, customer.getCustomerType(), userAccount.getAccountId(),companyId);
                                    if (contactList.size() == 0) {
                                        Customer cust1 = customerDbService.selectCustomerById(customer.getCustomerId());
                                        Boolean c = addContact(importVO, userAccount, cust1, contactId, companyId);
                                        if (c) {
                                            importNum = importNum + 1;
                                            continue;
                                        } else {
                                            content = "导入异常,联系人姓名:"+ importVO.getContactName() + ",主手机:"+ importVO.getContactInformation()
                                                    + ",电话:" + importVO.getInformation() + ",客户姓名:" + importVO.getCustomerName()
                                                    + ",所有人:" + importVO.getAccountName() + ",所属分公司:" + importVO.getCompanyName();
                                            //log.info("导入联系人异常:{}", content);
                                            insertImportFailureLog(importVO, 2, content, "",companyId,userAccount.getAccountId());
                                            importFailIdStr.add(i+2);
                                            continue;
                                        }
                                    } else {
                                        //insertImportFailureLog(importVO, 1, "联系人已存在", contactList.get(0).getContactId(),companyId);
                                        repeatIdStr.add(i+2);
                                        continue;
                                    }
                                } else {
                                    content = "没有电话号,联系人姓名:"+ importVO.getContactName() + ",主手机:"+ importVO.getContactInformation()
                                            + ",电话:" + importVO.getInformation() + ",客户姓名:" + importVO.getCustomerName()
                                            + ",所有人:" + importVO.getAccountName() + ",所属分公司:" + importVO.getCompanyName();
                                    insertImportFailureLog(importVO, 2, content, "",companyId,userAccount.getAccountId());
                                    importFailIdStr.add(i+2);
                                    continue;
                                }
                            }
                        }else{
                            content = "联系人姓名不存在,联系人姓名:"+ importVO.getContactName() + ",主手机:"+ importVO.getContactInformation()
                                    + ",电话:" + importVO.getInformation() + ",客户姓名:" + importVO.getCustomerName()
                                    + ",所有人:" + importVO.getAccountName() + ",所属分公司:" + importVO.getCompanyName();
                            insertImportFailureLog(importVO, 2, content, "",companyId,userAccount.getAccountId());
                            importFailIdStr.add(i+2);
                            continue;
                        }


                        /*if (StringUtils.isBlank(importVO.getInformation()) && StringUtils.isBlank(importVO.getContactInformation())) {
                            content = "没有电话号,联系人姓名:"+ importVO.getContactName() + ",主手机:"+ importVO.getContactInformation()
                                    + ",电话:" + importVO.getInformation() + ",客户姓名:" + importVO.getCustomerName()
                                    + ",所有人:" + importVO.getAccountName() + ",所属分公司:" + importVO.getCompanyName();
                            insertImportFailureLog(importVO, 2, content, "",companyId,userAccount.getAccountId());
                            importFailIdStr.add(i+2);
                            continue;
                        }*/

                    } else {
                        CustomerVO customerVO = customerDbService.selectCustomerByName(importVO.getCustomerName());
                        if(customerVO != null) {
                            Boolean bs = singleProductCustomerDbService.isSingleProductCustomerRepeat(customerVO.getCustomerId(), userAccount.getAccountId());
                            if(!bs) {
                                String singleProductCustomerId = CommonUtils.getGUID();
                                SingleProductCustomer singleProductCustomer = new SingleProductCustomer();
                                singleProductCustomer.setSingleProductCustomerId(singleProductCustomerId);
                                singleProductCustomer.setCustomerId(customerVO.getCustomerId());
                                singleProductCustomer.setDeleteStatus(Short.valueOf("0"));
                                singleProductCustomer.setCreatePeopleId(userAccount.getAccountId());
                                singleProductCustomer.setCreateTm(formatTime(importVO.getCreateTm()));
                                singleProductCustomer.setUpdatePeopleId(userAccount.getAccountId());
                                singleProductCustomer.setUpdateTm(new Date());
                                Boolean c = singleProductCustomerDbService.insertSingleProductCustomer(singleProductCustomer);
                                if (c) {
                                    importNum = importNum + 1;

                                    if (!StringUtils.isBlank(importVO.getContactInformation())) {
                                        if(importVO.getContactInformation().contains(",")){
                                            String[] split = importVO.getContactInformation().split(",");
                                            for(int j = 0; j < split.length; j++) {
                                                if(split[j].contains("-")) {
                                                    String info = split[j].replaceAll("-", "");
                                                    if(j == 0) {
                                                        addSingleProductCustomerContact(userAccount,importVO,singleProductCustomerId,info);
                                                    }else{
                                                        addSingleProductCustomerContact(userAccount,importVO,singleProductCustomerId,info);
                                                    }

                                                }else{
                                                    if(j == 0) {
                                                        addSingleProductCustomerContact(userAccount,importVO,singleProductCustomerId,split[j]);
                                                    }else{
                                                        addSingleProductCustomerContact(userAccount,importVO,singleProductCustomerId,split[j]);
                                                    }
                                                }
                                            }
                                        }else {
                                            if(importVO.getContactInformation().contains("-")) {
                                                String info = importVO.getContactInformation().replaceAll("-", "");
                                                addSingleProductCustomerContact(userAccount,importVO,singleProductCustomerId,info);
                                            }else{
                                                addSingleProductCustomerContact(userAccount,importVO,singleProductCustomerId,importVO.getContactInformation());
                                            }
                                        }
                                        if (!StringUtils.isBlank(importVO.getInformation())) {
                                            if (importVO.getInformation().contains(",")) {
                                                String[] informationArr = importVO.getInformation().split(",");
                                                for (String information : informationArr) {
                                                    if(information.contains("-")) {
                                                        String info = information.replaceAll("-", "");
                                                        addSingleProductCustomerContact(userAccount,importVO,singleProductCustomerId,info);
                                                    }else{
                                                        addSingleProductCustomerContact(userAccount,importVO,singleProductCustomerId,information);
                                                    }
                                                }

                                            } else {
                                                if(importVO.getInformation().contains("-")){
                                                    addSingleProductCustomerContact(userAccount,importVO,singleProductCustomerId,importVO.getInformation().replaceAll("-",""));
                                                }else{
                                                    addSingleProductCustomerContact(userAccount,importVO,singleProductCustomerId,importVO.getInformation());
                                                }

                                            }
                                        }
                                    } else {
                                        if (!StringUtils.isBlank(importVO.getInformation())) {
                                            if (importVO.getInformation().contains(",")) {
                                                String[] informationArr = importVO.getInformation().split(",");
                                                for (int j = 0; j < informationArr.length; j++) {
                                                    if(informationArr[j].contains("-")) {
                                                        String information = informationArr[j].replaceAll("-", "");
                                                        if (j == 0) {
                                                            addSingleProductCustomerContact(userAccount,importVO,singleProductCustomerId,information);
                                                        } else {
                                                            addSingleProductCustomerContact(userAccount,importVO,singleProductCustomerId,information);
                                                        }
                                                    }else{
                                                        if (j == 0) {
                                                            addSingleProductCustomerContact(userAccount,importVO,singleProductCustomerId,informationArr[j]);
                                                        } else {
                                                            addSingleProductCustomerContact(userAccount,importVO,singleProductCustomerId,informationArr[j]);
                                                        }
                                                    }
                                                }

                                            } else {
                                                if(importVO.getInformation().contains("-")){
                                                    addSingleProductCustomerContact(userAccount,importVO,singleProductCustomerId,importVO.getInformation().replaceAll("-",""));
                                                }else{
                                                    addSingleProductCustomerContact(userAccount,importVO,singleProductCustomerId,importVO.getInformation());
                                                }

                                            }
                                        }
                                    }

                                    continue;
                                } else {
                                    content = "导入异常,联系人姓名:"+ importVO.getContactName() + ",主手机:"+ importVO.getContactInformation()
                                            + ",电话:" + importVO.getInformation() + ",客户姓名:" + importVO.getCustomerName()
                                            + ",所有人:" + importVO.getAccountName() + ",所属分公司:" + importVO.getCompanyName();
                                    insertImportFailureLog(importVO, 2, content, "",companyId,userAccount.getAccountId());
                                    importFailIdStr.add(i+2);
                                    continue;
                                }
                            }

                        }else{
                            CustomerVO cust = customerDbService.selectCustomerByNameAndAccountId(importVO.getContactName(),userAccount.getAccountId(),"1",companyId);
                            if(cust == null) {
                                String contactId = CommonUtils.getGUID();
                                if(!StringUtils.isBlank(importVO.getContactName())){
                                    if (!StringUtils.isBlank(importVO.getContactInformation())) {
                                        String information = "";
                                        if(importVO.getContactInformation().contains(",")) {
                                            String[] split = importVO.getContactInformation().split(",");
                                            information = split[0];
                                        }else{
                                            information = importVO.getContactInformation();
                                        }
                                        information = containsLine(information);
                                        String customerId = addPersonalCustomer(importVO, userAccount,companyId);
                                        Customer cust1 = customerDbService.selectCustomerById(customerId);
                                        List<Contact> contactList = contactDbService.getCustomerIdAndContactNameAndAccountIdAndCompanyIds(customerId, importVO.getContactName(), information, "1", userAccount.getAccountId(),companyId);
                                        if (contactList.size() == 0) {
                                            Boolean c = addContact(importVO, userAccount, cust1, contactId, companyId);
                                            if (c) {
                                                importNum = importNum + 1;
                                                continue;
                                            } else {
                                                content = "导入异常,联系人姓名:"+ importVO.getContactName() + ",主手机:"+ importVO.getContactInformation()
                                                        + ",电话:" + importVO.getInformation() + ",客户姓名:" + importVO.getCustomerName()
                                                        + ",所有人:" + importVO.getAccountName() + ",所属分公司:" + importVO.getCompanyName();
                                                insertImportFailureLog(importVO, 2, content, "",companyId,userAccount.getAccountId());
                                                importFailIdStr.add(i+2);
                                                continue;
                                            }
                                        } else {
                                            //insertImportFailureLog(importVO, 1, "联系人已存在", contactList.get(0).getContactId(),companyId);
                                            repeatIdStr.add(i+2);
                                            continue;
                                        }
                                    } else {
                                        if (!StringUtils.isBlank(importVO.getInformation())) {
                                            String information = "";
                                            if (importVO.getInformation().contains(",")) {
                                                String[] informationArr = importVO.getInformation().split(",");
                                                information = informationArr[0];
                                            } else {
                                                information = importVO.getInformation();
                                            }
                                            information = containsLine(information);
                                            String customerId = addPersonalCustomer(importVO, userAccount,companyId);
                                            Customer cust1 = customerDbService.selectCustomerById(customerId);
                                            List<Contact> contactList = contactDbService.getCustomerIdAndContactNameAndAccountIdAndCompanyIds(customerId, importVO.getContactName(),information, "1", userAccount.getAccountId(),companyId);
                                            if (contactList.size() == 0) {
                                                Boolean c = addContact(importVO, userAccount, cust1, contactId, companyId);
                                                if (c) {
                                                    importNum = importNum + 1;
                                                    continue;
                                                } else {
                                                    content = "导入异常,联系人姓名:"+ importVO.getContactName() + ",主手机:"+ importVO.getContactInformation()
                                                            + ",电话:" + importVO.getInformation() + ",客户姓名:" + importVO.getCustomerName()
                                                            + ",所有人:" + importVO.getAccountName() + ",所属分公司:" + importVO.getCompanyName();
                                                    insertImportFailureLog(importVO, 2, content, "",companyId,userAccount.getAccountId());
                                                    importFailIdStr.add(i+2);
                                                    continue;
                                                }
                                            } else {
                                                //insertImportFailureLog(importVO, 1, "联系人已存在", contactList.get(0).getContactId(),companyId);
                                                repeatIdStr.add(i+2);
                                                continue;
                                            }
                                        } else {
                                            content = "没有电话号,联系人姓名:"+ importVO.getContactName() + ",主手机:"+ importVO.getContactInformation()
                                                    + ",电话:" + importVO.getInformation() + ",客户姓名:" + importVO.getCustomerName()
                                                    + ",所有人:" + importVO.getAccountName() + ",所属分公司:" + importVO.getCompanyName();
                                            insertImportFailureLog(importVO, 2, content, "",companyId,userAccount.getAccountId());
                                            importFailIdStr.add(i+2);
                                            continue;
                                        }
                                    }
                                }else{
                                    content = "联系人姓名不存在,联系人姓名:"+ importVO.getContactName() + ",主手机:"+ importVO.getContactInformation()
                                            + ",电话:" + importVO.getInformation() + ",客户姓名:" + importVO.getCustomerName()
                                            + ",所有人:" + importVO.getAccountName() + ",所属分公司:" + importVO.getCompanyName();
                                    insertImportFailureLog(importVO, 2, content, "",companyId,userAccount.getAccountId());
                                    importFailIdStr.add(i+2);
                                    continue;
                                }
                            }
                        }
                    }

                } else {
                    //导入失败
                    content = "所有人在表中没有,联系人姓名:"+ importVO.getContactName() + ",主手机:"+ importVO.getContactInformation()
                            + ",电话:" + importVO.getInformation() + ",客户姓名:" + importVO.getCustomerName()
                            + ",所有人:" + importVO.getAccountName() + ",所属分公司:" + importVO.getCompanyName();
                    insertImportFailureLog(importVO, 2, content, "",companyId,"");
                    importFailIdStr.add(i+2);
                    continue;
                }

            } catch (Exception e) {
                content = "导入异常,联系人姓名:"+ importVO.getContactName() + ",主手机:"+ importVO.getContactInformation()
                        + ",电话:" + importVO.getInformation() + ",客户姓名:" + importVO.getCustomerName()
                        + ",所有人:" + importVO.getAccountName() + ",所属分公司:" + importVO.getCompanyName();
                if(userAccount == null) {
                    insertImportFailureLog(importVO, 2, content, "",companyId,"");
                }else{
                    insertImportFailureLog(importVO, 2, content, "",companyId,userAccount.getAccountId());
                }

                importFailIdStr.add(i+2);
                log.error("导入联系人异常,content: {}, Exception info : {}", content, e);
            }
        }

        jsonObject.put("importNum",importNum);
        jsonObject.put("repeatIdStr",repeatIdStr);
        jsonObject.put("importFailIdStr",importFailIdStr);
        return jsonObject;
    }

    /**
     * 包含"-"去掉
     * @param information
     * @return
     */
    public String containsLine(String information) {
        if(information.contains("-")) {
            information = information.replaceAll("-","");
            return information;
        }else{
            return information;
        }
    }


    /**
     * 组装存储联系人信息
     */
    public Boolean addContact(ContactImportVO importVO, UserAccount userAccount, Customer customer, String contactId, String companyId) throws ParseException {
        Date createTm = null;
        Date updateTm = null;
        if (Objects.nonNull(importVO.getCreateTm()) || Objects.nonNull(importVO.getUpdateTm())) {
            createTm = formatTime(importVO.getCreateTm());
            updateTm = formatTime(importVO.getUpdateTm());
        }

        Contact contact = new Contact();
        CustomerContactPerson customerContactPerson = new CustomerContactPerson();

        contact.setContactId(contactId);
        contact.setCreateTm(createTm);
        contact.setCreatePeopleId(userAccount.getAccountId());
        contact.setUpdateTm(new Date());
        contact.setUpdatePeopleId(userAccount.getAccountId());
        contact.setContactNature(Integer.parseInt(customer.getCustomerType()));
        contact.setCustomerId(customer.getCustomerId());
        contact.setCompanyName(importVO.getCustomerName());


        contact.setContactName(importVO.getContactName());
        if (!StringUtils.isBlank(importVO.getContactInformation())) {
            if(importVO.getContactInformation().contains(",")){
                String[] informationArr = importVO.getContactInformation().split(",");
                if(informationArr[0].contains("-")){
                    contact.setContactInformation(informationArr[0].replaceAll("-",""));
                }else{
                    contact.setContactInformation(informationArr[0]);
                }
            }else{
                if(importVO.getContactInformation().contains("-")){
                    contact.setContactInformation(importVO.getContactInformation().replaceAll("-",""));
                }else{
                    contact.setContactInformation(importVO.getContactInformation());
                }
            }
        } else {
            if (!StringUtils.isBlank(importVO.getInformation())) {
                if (importVO.getInformation().contains(",")) {
                    String[] informationArr = importVO.getInformation().split(",");
                    if(informationArr[0].contains("-")) {
                        contact.setContactInformation(informationArr[0].replaceAll("-",""));
                    }else{
                        contact.setContactInformation(informationArr[0]);
                    }
                } else {
                    if(importVO.getInformation().contains("-")) {
                        contact.setContactInformation(importVO.getInformation().replaceAll("-",""));
                    }else{
                        contact.setContactInformation(importVO.getInformation());
                    }
                }
            }
        }
        contact.setMailBox(importVO.getMailBox());
        contact.setWx(importVO.getWx());
        contact.setCompanyAddress(importVO.getCompanyAddress());
        if (Objects.nonNull(importVO.getGender())) {
            if ("男".equals(importVO.getGender())) {
                contact.setGender(0);
            } else if ("女".equals(importVO.getGender())) {
                contact.setGender(1);
            }
        }
        contact.setDeleteStatus(Short.valueOf("0"));
        contact.setCompanyId(companyId);
        contact.setAccountId(userAccount.getAccountId());
        contact.setContactPosition(importVO.getContactPosition());
        contact.setProvinceName(importVO.getProvinceName());
        contact.setCityName(importVO.getCityName());
        if (Objects.nonNull(importVO.getOnTheJobSituation()) && "在职".equals(importVO.getOnTheJobSituation())) {
            contact.setOnTheJobSituation(0);
        } else {
            contact.setOnTheJobSituation(1);
        }
        if (Objects.nonNull(importVO.getContactState()) && "是".equals(importVO.getContactState())) {
            contact.setContactState(1);
        } else {
            contact.setContactState(2);
        }
        contact.setDataSource(1);  //导入的数据
        boolean b = contactDbService.addContact(contact);
        if (b) {
            //企业客户保存客户下联系人
            if("0".equals(customer.getCustomerType())){
                customerContactPerson.setCustomerContactPersonId(CommonUtils.getGUID());
                customerContactPerson.setCustomerId(customer.getCustomerId());
                customerContactPerson.setContactName(importVO.getContactName());
                customerContactPerson.setContactPosition(importVO.getContactPosition());
            /*if (Objects.nonNull(importVO.getContactPosition())) {
                if (importVO.getContactPosition().contains("财务")) {
                    customerContactPerson.setContactPosition("1");
                } else if (importVO.getContactPosition().contains("人力")) {
                    customerContactPerson.setContactPosition("2");
                } else if (importVO.getContactPosition().contains("0公司管理")) {
                    customerContactPerson.setContactPosition("0");
                } else {
                    customerContactPerson.setContactPosition("3");
                }
            } else {
                customerContactPerson.setContactPosition("3");
            }*/

                if (!StringUtils.isBlank(importVO.getContactInformation())) {
                    if(importVO.getContactInformation().contains(",")) {
                        String[] split = importVO.getContactInformation().split(",");
                        if(split[0].contains("-")) {
                            customerContactPerson.setContactInformation(split[0].replaceAll("-",""));
                        }else {
                            customerContactPerson.setContactInformation(split[0]);
                        }
                    }else{
                        if(importVO.getContactInformation().contains("-")) {
                            customerContactPerson.setContactInformation(importVO.getContactInformation().replaceAll("-",""));
                        }else {
                            customerContactPerson.setContactInformation(importVO.getContactInformation());
                        }
                    }

                } else {
                    if (!StringUtils.isBlank(importVO.getInformation())) {
                        if (importVO.getInformation().contains(",")) {
                            String[] informationArr = importVO.getInformation().split(",");
                            if(informationArr[0].contains("-")) {
                                customerContactPerson.setContactInformation(informationArr[0].replaceAll("-",""));
                            }else{
                                customerContactPerson.setContactInformation(informationArr[0]);
                            }
                        } else {
                            if(importVO.getInformation().contains("-")){
                                customerContactPerson.setContactInformation(importVO.getInformation().replaceAll("-",""));
                            }else{
                                customerContactPerson.setContactInformation(importVO.getInformation());
                            }
                        }
                    }
                }

                if (Objects.nonNull(importVO.getOnTheJobSituation()) && "在职".equals(importVO.getOnTheJobSituation())) {
                    customerContactPerson.setOnTheJobSituation(0);
                } else {
                    customerContactPerson.setOnTheJobSituation(1);
                }
                customerContactPerson.setIsSeniorExecutive(1);
                customerContactPerson.setMailBox(importVO.getMailBox());
                customerContactPerson.setWx(importVO.getWx());
                customerContactPerson.setCreatePeopleId(userAccount.getAccountId());
                customerContactPerson.setCreateTm(createTm);
                customerContactPerson.setUpdatePeopleId(userAccount.getAccountId());
                customerContactPerson.setUpdateTm(new Date());

                if (Objects.nonNull(importVO.getContactState()) && "是".equals(importVO.getContactState())) {
                    customerContactPerson.setContactState(1);
                } else {
                    customerContactPerson.setContactState(2);
                }
                customerContactPerson.setDataSource(1);  //导入的数据
                customerContactPerson.setCompanyId(companyId);
                customerPoolDbService.addCustomerContactPerson(customerContactPerson);
            }



            if (!StringUtils.isBlank(importVO.getContactInformation())) {
                if(importVO.getContactInformation().contains(",")){
                    String[] split = importVO.getContactInformation().split(",");
                    for(int j = 0; j < split.length; j++) {
                        if(split[j].contains("-")) {
                            String info = split[j].replaceAll("-", "");
                            if(j == 0) {
                                addInformation(info, contactId, customer.getCustomerId(), userAccount.getAccountId(), createTm, updateTm, 0,companyId);
                            }else{
                                addInformation(info, contactId, customer.getCustomerId(), userAccount.getAccountId(), createTm, updateTm, 1,companyId);
                            }

                        }else{
                            if(j == 0) {
                                addInformation(split[j], contactId, customer.getCustomerId(), userAccount.getAccountId(), createTm, updateTm, 0,companyId);
                            }else{
                                addInformation(split[j], contactId, customer.getCustomerId(), userAccount.getAccountId(), createTm, updateTm, 1,companyId);
                            }
                        }
                    }
                }else {
                    if(importVO.getContactInformation().contains("-")) {
                        String info = importVO.getContactInformation().replaceAll("-", "");
                        addInformation(info, contactId, customer.getCustomerId(), userAccount.getAccountId(), createTm, updateTm, 0,companyId);
                    }else{
                        addInformation(importVO.getContactInformation(), contactId, customer.getCustomerId(), userAccount.getAccountId(), createTm, updateTm, 0,companyId);
                    }
                }
                if (!StringUtils.isBlank(importVO.getInformation())) {
                    if (importVO.getInformation().contains(",")) {
                        String[] informationArr = importVO.getInformation().split(",");
                        for (String information : informationArr) {
                            if(information.contains("-")) {
                                String info = information.replaceAll("-", "");
                                addInformation(info, contactId, customer.getCustomerId(), userAccount.getAccountId(), createTm, updateTm, 1,companyId);
                            }else{
                                addInformation(information, contactId, customer.getCustomerId(), userAccount.getAccountId(), createTm, updateTm, 1,companyId);
                            }
                        }

                    } else {
                        if(importVO.getInformation().contains("-")){
                            addInformation(importVO.getInformation().replaceAll("-",""), contactId, customer.getCustomerId(), userAccount.getAccountId(), createTm, updateTm, 1,companyId);
                        }else{
                            addInformation(importVO.getInformation(), contactId, customer.getCustomerId(), userAccount.getAccountId(), createTm, updateTm, 1,companyId);
                        }

                    }
                }
            } else {
                if (!StringUtils.isBlank(importVO.getInformation())) {
                    if (importVO.getInformation().contains(",")) {
                        String[] informationArr = importVO.getInformation().split(",");
                        for (int j = 0; j < informationArr.length; j++) {
                            if(informationArr[j].contains("-")) {
                                String information = informationArr[j].replaceAll("-", "");
                                if (j == 0) {
                                    addInformation(information, contactId, customer.getCustomerId(), userAccount.getAccountId(), createTm, updateTm, 0,companyId);
                                } else {
                                    addInformation(information, contactId, customer.getCustomerId(), userAccount.getAccountId(), createTm, updateTm, 1,companyId);
                                }
                            }else{
                                if (j == 0) {
                                    addInformation(informationArr[j], contactId, customer.getCustomerId(), userAccount.getAccountId(), createTm, updateTm, 0,companyId);
                                } else {
                                    addInformation(informationArr[j], contactId, customer.getCustomerId(), userAccount.getAccountId(), createTm, updateTm, 1,companyId);
                                }
                            }
                        }

                    } else {
                        if(importVO.getInformation().contains("-")){
                            addInformation(importVO.getInformation().replaceAll("-",""), contactId, customer.getCustomerId(), userAccount.getAccountId(), createTm, updateTm, 0,companyId);
                        }else{
                            addInformation(importVO.getInformation(), contactId, customer.getCustomerId(), userAccount.getAccountId(), createTm, updateTm, 0,companyId);
                        }

                    }
                }
            }
        }
        return b;
    }

    /**
     * 添加个人客户
     * @param importVO
     * @param userAccount
     * @return
     * @throws ParseException
     */
    public String addPersonalCustomer(ContactImportVO importVO,UserAccount userAccount,String companyId) throws ParseException {
        Date createTm = null;
        if (Objects.nonNull(importVO.getCreateTm())) {
            createTm = formatTime(importVO.getCreateTm());
        }
        String customerId = CommonUtils.getGUID();
        Customer customer = new Customer();
        customer.setCustomerId(customerId);
        customer.setCustomerName(importVO.getContactName());
        customer.setCustomerNumber(createCustomerNumber());
        customer.setCustomerType("1"); //个人客户

        if (!StringUtils.isBlank(importVO.getContactInformation())) {
            if(importVO.getContactInformation().contains(",")){
                String[] informationArr = importVO.getContactInformation().split(",");
                if(informationArr[0].contains("-")){
                    customer.setContactPersonPhone(informationArr[0].replaceAll("-",""));
                }else{
                    customer.setContactPersonPhone(informationArr[0]);
                }
            }else{
                if(importVO.getContactInformation().contains("-")){
                    customer.setContactPersonPhone(importVO.getContactInformation().replaceAll("-",""));
                }else{
                    customer.setContactPersonPhone(importVO.getContactInformation());
                }
            }
        } else {
            if (!StringUtils.isBlank(importVO.getInformation())) {
                if (importVO.getInformation().contains(",")) {
                    String[] informationArr = importVO.getInformation().split(",");
                    if(informationArr[0].contains("-")) {
                        customer.setContactPersonPhone(informationArr[0].replaceAll("-",""));
                    }else{
                        customer.setContactPersonPhone(informationArr[0]);
                    }
                } else {
                    if(importVO.getInformation().contains("-")) {
                        customer.setContactPersonPhone(importVO.getInformation().replaceAll("-",""));
                    }else{
                        customer.setContactPersonPhone(importVO.getInformation());
                    }
                }
            }
        }
        customer.setOwnerId(userAccount.getAccountId());
        customer.setCurrentStatus(Short.parseShort("1"));
        customer.setOldCustomer(1);

        //customer.setContactPersonPhone(importVO.getContactInformation());

        customer.setCompanyName(companyId);
        //customer.setDetailedAddress(customerContactVO.getCompanyAddress());
        customer.setAccountId(userAccount.getAccountId());
        customer.setCreatePeopleId(userAccount.getAccountId());
        customer.setCreateTm(createTm);
        customer.setUpdatePeopleId(userAccount.getAccountId());
        customer.setUpdateTm(new Date());
        customer.setDeleteStatus(Short.parseShort(String.valueOf(StatusCodeEnum.NORMAL_CODE.getState())));
        //查询全国默认池 客户的
        CustomerPool customerPool = customerPoolDbService.selectCustomerPoolByName("全国默认池");
        if (customerPool != null) {
            customer.setCustomerPoolId(customerPool.getCustomerPoolId());
        }
        customerDbService.insertCustomer(customer);
        return customerId;
    }

    /**
     * 添加单品客户
     * @param userAccount 用户类
     * @param importVO 联系人导入数据
     * @throws ParseException
     */
    public void addSingleProductCustomerContact(UserAccount userAccount,ContactImportVO importVO,String singleProductCustomerId,String information) throws ParseException {
        SingleProductCustomerContact singleProductCustomerContact = new SingleProductCustomerContact();
        singleProductCustomerContact.setSingleProductCustomerContactId(CommonUtils.getGUID());
        singleProductCustomerContact.setContactName(importVO.getContactName());
        singleProductCustomerContact.setContactPosition(importVO.getContactPosition());
        singleProductCustomerContact.setContactInformation(information);
        if (Objects.nonNull(importVO.getOnTheJobSituation()) && "在职".equals(importVO.getOnTheJobSituation())) {
            singleProductCustomerContact.setOnTheJobSituation(0);
        } else {
            singleProductCustomerContact.setOnTheJobSituation(1);
        }
        singleProductCustomerContact.setIsSeniorExecutive(1);
        singleProductCustomerContact.setMailBox(importVO.getMailBox());
        singleProductCustomerContact.setWeChat(importVO.getWx());
        singleProductCustomerContact.setDeleteStatus(Short.valueOf("0"));
        singleProductCustomerContact.setCreatePeopleId(userAccount.getAccountId());
        singleProductCustomerContact.setCreateTm(formatTime(importVO.getCreateTm()));
        singleProductCustomerContact.setUpdatePeopleId(userAccount.getAccountId());
        singleProductCustomerContact.setUpdateTm(new Date());
        singleProductCustomerContact.setSingleProductCustomerId(singleProductCustomerId);
        singleProductCustomerContactDbService.addSingleProductCustomerContact(singleProductCustomerContact);
    }

    /**
     * 生成客户编号
     *
     * @return
     */
    public String createCustomerNumber() {
        String datetime = new SimpleDateFormat("yyyyMMdd").format(new Date());
        String newCustomerNumber = datetime + "00001";
        String maxCustomerNumber = customerDbService.selectMaxCustomerNumber(datetime);
        if (Objects.nonNull(maxCustomerNumber)) {
            if (maxCustomerNumber.length() < 8) {
                maxCustomerNumber = customerDbService.selectMaxCustomerNumber(datetime);
                if (Objects.isNull(maxCustomerNumber)) {
                    return newCustomerNumber;
                }
            }
            if (datetime.equals(maxCustomerNumber.substring(0, 8))) {
                newCustomerNumber = datetime + String.format("%05d", Integer.parseInt(maxCustomerNumber.substring(8)) + 1);
            }
        }
        return newCustomerNumber;
    }

    /**
     * 记录导入失败日志
     * @param importVO
     * @param type
     */
    public void insertImportFailureLog(ContactImportVO importVO,Integer type,String content,String contactId,String companyId,String accountId){
        SysCompany sysCompany = sysCompanyDbService.selectSysCompanyById(companyId);
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();//当前登录人信息
        List<ImportFailureLog> list = importFailureLogDbService.selectImportFailureLog(content,"7",companyId,accountId);
        if(list == null || list.size() == 0){
            ImportFailureLog importFailureLog = new ImportFailureLog();
            if (type == 1){
                if(!StringUtils.isBlank(contactId)) {
                    importFailureLog.setDataId(contactId);
                }
            }

            importFailureLog.setImportFailureLogId(CommonUtils.getGUID());
            importFailureLog.setOperatePeopleId(userAccount.getAccountId());
            importFailureLog.setOperateTime(new Date());
            importFailureLog.setOperateType("7");
            importFailureLog.setImportName(importVO.getContactName());
            importFailureLog.setReasonForFailure(content);
            importFailureLog.setImportData(JSONObject.toJSONString(importVO));
            importFailureLog.setLogType(String.valueOf(type));
            importFailureLog.setAccountId(accountId);
            importFailureLog.setCompanyId(companyId);
            importFailureLogDbService.insertImportFailureLog(importFailureLog);

            if(sysCompany !=null && !StringUtils.isBlank(sysCompany.getCompanyName())) {
                if(sysCompany.getCompanyName().equals(importVO.getCompanyName())) {
                    if(!"联系人已存在".equals(content)){
                        ContactErrorRecord contactErrorRecord = new ContactErrorRecord();
                        contactErrorRecord.setContactErrorRecordId(CommonUtils.getGUID());
                        contactErrorRecord.setCustomerName(importVO.getCustomerName());
                        contactErrorRecord.setContactName(importVO.getContactName());
                        contactErrorRecord.setContactInformation(importVO.getContactInformation());
                        contactErrorRecord.setInformation(importVO.getInformation());
                        contactErrorRecord.setAllName(importVO.getAccountName());
                        contactErrorRecord.setCreatePeopleId(userAccount.getAccountId());
                        contactErrorRecord.setCreateTm(new Date());
                        contactErrorRecord.setUpdatePeopleId(userAccount.getAccountId());
                        contactErrorRecord.setUpdateTm(new Date());
                        contactErrorRecord.setAccountId(userAccount.getAccountId());
                        contactErrorRecord.setCompanyId(companyId);
                        contactDbService.insertContactErrorRecord(contactErrorRecord);
                    }
                }
            }
        }


    }

    /**
     * 添加联系方式
     * @param
     * @return
     */
    public void addInformation(String information,String contactId,String customerId,String accountId,Date createTm,Date updateTm,int contactInformationType,String company) {
        ContactInformation contactInformation = new ContactInformation();
        contactInformation.setContactInformationId(CommonUtils.getGUID());
        contactInformation.setContactInformation(information);
        contactInformation.setContactId(contactId);
        contactInformation.setCustomerId(customerId);
        contactInformation.setContactType("单位电话");
        contactInformation.setContactInformationType(contactInformationType);
        contactInformation.setCreatePeopleId(accountId);
        contactInformation.setCreateTm(createTm);
        contactInformation.setUpdatePeopleId(accountId);
        contactInformation.setUpdateTm(new Date());
        contactInformation.setDataSource(1);
        contactInformation.setCompanyId(company);
        contactInformationDbService.addContactInformation(contactInformation);
    }

    /**
     * 转时间格式
     * @param date 创建时间  结束时间
     * @return
     */
    public Date formatTime(String date) throws ParseException {
        //同一个Excel有不一样的时间格式……
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        return simpleDateFormat.parse(date);
    }
}
